import React from 'react';
import { Row, Col, Button, Tooltip, Modal, message, Switch } from 'antd';
import {
  WeaTools,
  WeaFormItem,
  WeaInput,
  WeaTop,
  WeaBrowser,
  WeaRangePicker,
  WeaScope,
  WeaTable,
  WeaDialog,
  WeaDatePicker,
} from 'ecCom';

const style = {
  width: '25%',
  float: 'left',
  marginTop: 8,
  padding: '0 20px'
};

const initStateM = {
  params: {
    url: '',
    userid: '',
    createdate_start: '',
    createdate_end: '',
    accesstime_start: '',
    accesstime_end: '',
  },
  useridDatas: [],
};

const initStateMClear = {
  cparams: {
    url: '',
    userid: '',
    createdate_start: '',
    createdate_end: '',
  },
  cuseridDatas: [],
};

export default class Mobile extends React.Component {
  state = { ...initStateM, datas: [], y: 0, ...initStateMClear, visible: false, current: 0, pageSize: 10, loading: false };

  componentDidMount() {
    this.componentDidUpdate();
    this.setState({ loading: true });
    WeaTools.callApi('/api/ec/dev/util/getAccessPageList', 'GET', this.state.params).then(result => {
      this.setState({ datas: result.data || [], loading: false, current: 0 });
    });
  }

  componentDidUpdate() {
    if (this.table) {
      const { y } = this.state;
      try {
        const h = document.documentElement.clientHeight - 100 - $(ReactDOM.findDOMNode(this.table)).offset().top;
        if (h !== y) {
          this.setState({ y: h });
        }
      } catch(e) {
        console.log('e: ', e);
      }
    }
  }

  renderDialog = () => {
    const { visible, cparams, cuseridDatas } = this.state;
    const labels = {
      url: '页面地址',
      userid: '用户',
      createdate_start: '日期之后',
      createdate_end: '日期之前',
    };
    const items = Object.keys(cparams).map(k => {
      let content = (
        <WeaInput
          value={cparams[k]}
          onChange={v => this.setState({ cparams: { ...cparams, [k]: v } })}
        />
      );
      if (k === 'userid') {
        content = (
          <WeaBrowser
            type={17}
            textDecoration={true}
            replaceDatas={this.state[`c${k}Datas`]}
            isSingle={false}
            onChange={(ids, names, datas)=> {
              this.setState({
                cparams: { ...this.state.cparams , [k]: ids },
                [`c${k}Datas`]: datas
              })
            }}
          />
        );
      }
      if (k === 'createdate_start' || k === 'createdate_end') {
        content = (
          <WeaDatePicker
            value={cparams[k]}
            onChange={v => this.setState({ cparams: { ...cparams, [k]: v } })}
          />
        );
      }
      return (
        <WeaFormItem
          key={k}
          label={labels[k]}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{
            marginTop: 8,
            padding: '0 20px'
          }}
        >
          {content}
        </WeaFormItem>
      );
    });
    let content = '确定要清理：';
    const arr = [];
    if (cparams.url) {
      arr.push(`地址为 ${cparams.url} 的`);
    }
    if (cparams.userid) {
      arr.push(`用户名为 ${cuseridDatas.map(d => d.showname || d.name)} 的`);
    }
    if (cparams.createdate_start) {
      arr.push(`${cparams.createdate_start} 之后的`);
    }
    if (cparams.createdate_end) {
      arr.push(`${cparams.createdate_end} 之前的`);
    }
    if (arr.length === 0) {
      content = '筛选条件为空！确定删除全部数据？';
    } else {
      content += `${arr.join(' ，')}数据？`;
    }
    const buttons = [
      (<Button type="primary" onClick={() => {
        Modal.confirm({
          content,
          onOk: () => {
            WeaTools.callApi('/api/ec/dev/util/clearaccesspage', 'POST', this.state.cparams).then(result => {
              if (result.status) {
                message.success('清理成功');
                this.setState({ ...initStateMClear, visible: false });
                this.componentDidMount();
              } else {
                message.error('清理失败，请重试');
              }
            });
          },
        })
      }}>{arr.length === 0 ? '清理全部数据' : '清理'}</Button>),
      (<Button type="primary" onClick={() => this.setState(initStateMClear)}>重置</Button>),
    ]
    return (
      <WeaDialog
        title="清理数据"
        onCancel={()=> this.setState({ visible: false })}
        visible={visible}
        style={{ width: 600, height: 200}}
        buttons={buttons}
      >
        <div style={{ paddingTop: 15 }} >
          {items}
        </div>
      </WeaDialog>
    )
  }

  render() {
    const { location: { query: { admin } } } = this.props;
    const { params, datas, y, current, pageSize, loading } = this.state;
    const labels = {
      url: '页面地址',
      userid: '用户名',
      accesstime_start: '耗时区间',
      accesstime_end: '耗时区间',
      createdate_start: '起止日期',
      createdate_end: '起止日期',
    };
    const items = Object.keys(params).map(k => {
      let content = (
        <WeaInput
          value={params[k]}
          onChange={v => this.setState({ params: { ...params, [k]: v } })}
          onKeyDown={e => {
            if (e.keyCode && e.keyCode === 13) {
              this.componentDidMount();
              e.preventDefault();
            }
          }}
        />
      );
      if (k === 'userid') {
        content = (
          <WeaBrowser
            type={17}
            textDecoration={true}
            replaceDatas={this.state[`${k}Datas`]}
            isSingle={false}
            onChange={(ids, names, datas)=> {
              this.setState({
                params: { ...this.state.params , [k]: ids },
                [`${k}Datas`]: datas
              })
            }}
          />
        );
      }
      if (k === 'createdate_start') {
        content = (
          <WeaRangePicker
            value={[params.createdate_start, params.createdate_end]}
            onChange={v => this.setState({
              params: {
                ...params,
                createdate_start: v[0] || '',
                createdate_end: v[1] || '',
              }
            })}
          />
        );
      }
      if (k === 'accesstime_start') {
        content = (
          <WeaScope
            isMobx
            value={[params.accesstime_start, params.accesstime_end]}
            onChange={v => this.setState({
              params: {
                ...params,
                accesstime_start: v[0] || '',
                accesstime_end: v[1] || '',
              }
            })}
          />
        );
      }
      if (k === 'createdate_end' || k === 'accesstime_end') return null;
      return (
        <WeaFormItem
          key={k}
          label={labels[k]}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={style}
        >
          {content}
        </WeaFormItem>
      );
    });
    const btns = [
      <Button type='primary' onClick={() => this.componentDidMount()}>查询</Button>,
      <Button type='primary' onClick={() => this.setState(initStateM)}>重置</Button>,
    ];
    if (admin) {
      btns.push(<Button type='primary' onClick={() => this.setState({ visible: true })}>打开数据清理</Button>);
    }
    const divStyle = {
      display: 'inline-block',
      float: 'left',
      height: 18,
      overflow: 'hidden',
      textAlign: 'center',
      cursor: 'pointer',
      marginTop: 2,
      marginRight: 1,
      minWidth: 20,
      maxWidth: 600,
    };
    const columns = [{
      title: '用户ID',
      dataIndex: 'USERID',
      key: 'USERID',
      width: 88,
    },{
      title: '用户名',
      dataIndex: 'lastname',
      key: 'lastname',
      width: 88,
    },{
      title: '记录时间',
      dataIndex: 'CREATEDATE',
      key: 'CREATEDATE',
      width: 88,
      render: (t, r) => {
        return `${r.CREATEDATE} ${r.CREATETIME}`;
      },
      sorter: (a, b) => new Date(`${a.CREATEDATE} ${a.CREATETIME}`).getTime() - new Date(`${b.CREATEDATE} ${b.CREATETIME}`).getTime(),
    }, {
      title: '页面地址',
      dataIndex: 'URL',
      key: 'URL',
      sorter: (a, b) => a.URL > b.URL,
      width: 200,
    }, {
      title: '总耗时',
      dataIndex: 'ACCESSTIME',
      key: 'ACCESSTIME',
      width: 100,
      render: (t, r) => {
        return `${r.ACCESSTIME} ms`;
      },
      sorter: (a, b) => a.ACCESSTIME - b.ACCESSTIME,
    }, {
      title: '详细耗时信息（毫秒/ms）',
      dataIndex: 'PARAM',
      key: 'PARAM',
      render: (t, r) => {
        if (r.PARAM) {
          try{
            const param = JSON.parse(r.PARAM);
            const endTypeList = {
              setTimeout5000: '总耗时超过5秒',
              changeLang: '设置多语言结束',
              mainJsLoaded: 'main.js 加载结束',
              getlocal: '多语言标签加载结束',
            }
            const labels = {
              head: 'head 加载耗时',
              js: 'js 依赖加载耗时',
              ssoInit: '单点登录耗时',
              getClientInfo: '获取 em 配置耗时',
              getActiveLanguage: '获取多语言列表耗时',
              changeLang: '设置多语言耗时',
              mainJsLoaded: 'main.js 加载耗时',
              getLabel: '获取多语言标签耗时',
            };
            const ssolabels = {
              sso_api: '单点登录 test 接口耗时',
              sso_config: 'config.js 耗时',
              sso_em: 'jem.js 耗时',
            };
            const labelKeys = Object.keys(labels);
            const ssolabelKeys = Object.keys(ssolabels);
            const renderLabel = (arr, l, info) => (
              <div style={{ width: '100%' }}>
                {
                  arr.map((k, i) => {
                    const t = (info ? info[k] : param[k]) || 0;
                    const width = Math.ceil(t / 2);
                    if (t === 0) return null;
                    return (
                      <Tooltip
                        placement="top"
                        title={
                          <div>
                            <p>{l[k] || k}</p>
                            <p>{`${t} ms`}</p>
                          </div>
                        }
                      >
                        <div
                          style={{
                            ...divStyle,
                            width,
                            background: t >= 500 ? '#fe5d5f' : t >= 300 ? '#ffe59d' : i % 2 === 0 ? '#94ddfc' : '#c9fcd2',
                          }}
                        >
                          {t}
                        </div>
                      </Tooltip>
                    );
                  })
                }
                <div style={{ clear: 'both' }} />
              </div>
            );
            const detailinfo = {};
            if (r.DETAILINFO) {
              try {
                const a = JSON.parse(r.DETAILINFO);
                if (Array.isArray(a) && a.length > 0) {
                  a.forEach(d => {
                    const da = d.split('|');
                    const key = `${da[1].replace(/^http(s?)\:\/\/[^\/]+[\/]/, '')}`;
                    if (!detailinfo.hasOwnProperty(key)) {
                      detailinfo[key] = da[0];
                    }
                  })
                }
              } catch(e) {
                console.log('e: ', e);
              }
            }
            const detailinfoKeys = Object.keys(detailinfo);
            return (
              <div style={{ width: '100%' }}>
                <p>总耗时 记录类型(endType): {`${param.endType} / ${endTypeList[param.endType]}`}</p>
                {renderLabel(labelKeys, labels)}
                <p style={{ marginTop: 5 }}>ssoInit 单点登录详细耗时：</p>
                {renderLabel(ssolabelKeys, ssolabels)}
                <p style={{ marginTop: 5 }}>主要接口服务器耗时：</p>
                {renderLabel(detailinfoKeys, {}, detailinfo)}
              </div>
            );
          } catch(e) {
            console.log('e: ', e);
          }
        }
        return t;
      },
    },{
      title: '设备',
      dataIndex: 'UA',
      key: 'UA',
      render: (t, r) => {
        if (!r.UA) return null;
        return (
          <Tooltip
            placement="topRight"
            title={r.UA}
          >
            <a href="javascript:void(0)" style={{ textDecoration: 'underline', color: '#2db7f5' }}>显示</a>
          </Tooltip>
        )
      },
      width: 60,
    }];
    const pagination = {
      current,
      pageSize,
      total: datas.length,
      showSizeChanger: true,
      onShowSizeChange: (c, p) => {
        this.setState({ pageSize: p });
      },
      onChange: (c) => {
        this.setState({ current: c });
      },
    };
    return (
      <div>
        <WeaTop
          loading={loading}
          icon={<i className="icon-coms-search" />}
          iconBgcolor="#57c5f7"
          title="性能查询-移动端"
          buttons={btns}
        />
        <Row style={{ padding: 20 }}>
          <Col span={24}>
            {items}
          </Col>
        </Row>
        <WeaTable
          ref={el => (this.table = el)}
          columns={columns}
          dataSource={datas}
          scroll={{ y }}
          pagination={pagination}
          loading={loading}
        />
        {this.renderDialog()}
      </div>
    );
  }
}